package com.example.playbox

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.playbox.bean.Game
import com.example.playbox.utils.MySQLiteOpenHelper

class DeleteGamesActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var etGameid: EditText
    private lateinit var etGamename: EditText
    private lateinit var etGametime: EditText
    private lateinit var etGamenote: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_delete_games)
        initView()
    }

    private fun initView() {
        etGameid = findViewById(R.id.et_gameid)
        val btnSearch: Button = findViewById(R.id.btn_search)
        etGamename = findViewById(R.id.et_gamename)
        etGametime = findViewById(R.id.et_gametime)
        etGamenote = findViewById(R.id.et_gamenote)
        val btnDelete: Button = findViewById(R.id.btn_delete)

        btnSearch.setOnClickListener(this)
        btnDelete.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.btn_search -> searchOrder()
            R.id.btn_delete -> deleteOrder()
        }
    }

    private fun searchOrder() {
        val gameid = etGameid.text.toString().trim()
        val dao = MySQLiteOpenHelper(applicationContext)
        dao.open()
        val game = dao.getGames(gameid)
        etGamename.setText(game.gameName)
        etGametime.setText(game.gameTime)
        etGamenote.setText(game.gameNote)
        dao.close()
    }

    private fun deleteOrder() {
        val gameid = etGameid.text.toString().trim()
        val currentUsername = getCurrentUsername()
        val dao = MySQLiteOpenHelper(applicationContext)
        dao.open()
        val game = dao.getGames(gameid)

        if (game.userName != currentUsername) {
            Toast.makeText(this, "您没有权限删除此游戏信息", Toast.LENGTH_SHORT).show()
            dao.close()
            return
        }

        val result = dao.deletGames(game)
        if (result > 0) {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show()
        }
        dao.close()
    }

    private fun getCurrentUsername(): String {
        val sp = getSharedPreferences("loginInfo", MODE_PRIVATE)
        return sp.getString("loginUserName", "") ?: ""
    }
}